import java.io.File;
import javax.xml.bind.annotation.XmlRootElement;

import codeg.CodeGeneration;
import codeg.CodeGenerationContext;
import codeg.Codeg;
import codeg.CodegException;

@XmlRootElement
public class FileCodeg extends Codeg 
{
	private File path = null;
	private boolean read = true, write = false, binary = false;
	
	public FileCodeg() { super(); }
	
    public File setPath(File path) {
        return this.path = path;
    }

	public File getPath() {
		return path;
	}

    public boolean isRead() {
        return read;
    }

    public void setRead(boolean read) {
        this.read = read;
    }

    public boolean isWrite() {
        return write;
    }

    public void setWrite(boolean write) {
        this.write = write;
    }

    public boolean isBinary() {
        return binary;
    }

    public void setBinary(boolean binary) {
        this.binary = binary;
    }
    
    @Override
    public CodeGeneration getCode(CodeGenerationContext context) throws CodegException {
        CodeGeneration code = new CodeGeneration(this);

        /* This codeg only generates Java code currently */
        if (context.getLanguage() != CodeGenerationContext.LANGUAGE.JAVA)
            return code;
        
        boolean r = isRead();
        boolean w = isWrite();
        boolean b = isBinary();
        
        if (r)
            if (b)
                code.setImports(new String[] { "java.io.File", "java.io.FileInputStream" });
            else
                code.setImports(new String[] { "java.io.File", "java.io.DataInputStream" });
        else if (w) {
            if (b)
                code.setImports(new String[] { "java.io.File", "java.io.FileOutputStream" });
            else
                code.setImports(new String[] { "java.io.File", "java.io.DataOutputStream" });
        }
        
        
        if (getPath() == null)
            code.setLocalCode("");
        else if (r)
            if (b)
                code.setLocalCode("FileInputStream " + getId() + " = new FileInputStream(new File(\"" + getPath().toString() + "\"))");
            else
                code.setLocalCode("DataInputStream " + getId() + " = new DataInputStream(new File(\"" + getPath().toString() + "\"))");
        else if (w) {
            if (b)
                code.setLocalCode("FileOutputStream " + getId() + " = new FileOutputStream(new File(\"" + getPath().toString() + "\"))");
            else
                code.setLocalCode("DataOutputStream " + getId() + " = new DataInputStream(new File(\"" + getPath().toString() + "\"))");
        }
        
        return code;
    }
}